<template>
  <div>
    <div class="header">
      <button @click="$emit('back')">返回</button>
      <span>服务器编号: {{ jobId }}</span>
      <span>操作系统版本: Random OS</span>
    </div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="task in tasks" :key="task.task_id">
          <td>{{ task.task_id }}</td>
          <td>{{ task.job_id }}</td>
          <td>{{ task.os }}</td>
          <td>{{ task.queue_time }}</td>
          <td>{{ task.start_time }}</td>
          <td>{{ task.end_time }}</td>
          <td>{{ task.cpu_count }}</td>
          <td>{{ task.memory_gb }}</td>
          <td>{{ task.status }}</td>
          <td><div class="progress" :style="{ width: task.progress + '%' }"></div></td>
          <td>
            <button v-if="task.status !== 'waitting'" @click="showLog(task.task_id)">日志查看</button>
            <button v-if="task.status !== 'waitting'" @click="downloadLog(task.task_id)">日志下载</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">分页: {{ pageId }}</div>
  </div>
</template>

<script>
import { getTaskList, showTaskLog, downloadTaskLog } from '../api';

export default {
  props: ['jobId'],
  data() {
    return {
      headers: [
        'Task编号', 'Job编号', '运行操作系统', '排队时间', '开始时间', '结束时间',
        '占用cpu数量', '占用内存数量(GB)', 'status', '进度', '操作',
      ],
      tasks: [],
      pageId: 1,
    };
  },
  created() {
    this.fetchTasks();
  },
  methods: {
    async fetchTasks() {
      const res = await getTaskList({ page_id: this.pageId, env_id: this.jobId });
      this.tasks = res.data;
    },
    async showLog(taskId) {
      const res = await showTaskLog(taskId);
      alert(res.data);
    },
    async downloadLog(taskId) {
      const res = await downloadTaskLog(taskId);
      const blob = new Blob([res.data]);
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${taskId}_log.txt`;
      link.click();
    },
  },
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.progress {
  height: 10px;
  background: #4caf50;
}
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}
button {
  margin: 0 5px;
}
.pagination {
  margin-top: 10px;
  text-align: center;
}
</style>
